let titles = []; // 存储题目数据
let cuoti = []; // 存储错题数据
const app = getApp();

let startTime;
let currentQuestionTime = 0;
let timer;

// 定义计算得分的函数
function calculateScore(userAnswer, correctAnswer) {
  return userAnswer === correctAnswer ? 1 : 0;
}

// 定义统计错题的函数
function collectCuoti(userAnswer, correctAnswer) {
  return userAnswer !== correctAnswer;
}

Page({
  data: {
    total: 0,
    isSelect: false,
    subject: null,
    userSelect: '',
    userScore: 0,
    totalScore: -1,
    totalError: 0,
    current: 1,
    correctAnswer: '',
    explain: '',
    hasAnsweredFirstQuestion: false,
    showFinishButton: false,
    answered: [], // 记录每个题目的答题状态
    correctCount: 0, // 记录答对题目的数量
    currentTime: '', // 用于显示当前页面的时间
  },

  onLoad() {
    wx.cloud.database().collection('timu')
      .where({ type: "单选" })
      .get()
      .then(res => {
        console.log('题库数据', res);
        let allTitles = res.data;

        // 随机选择10道题目
        let shuffledTitles = allTitles.sort(() => Math.random() - 0.5);
        titles = shuffledTitles.slice(0, 10);

        titles.forEach((item, index) => {
          item.serialNumber = index + 1;
        });
        this.setData({
          subject: titles[0],
          total: titles.length,
          answered: new Array(titles.length).fill(false) // 初始化answered数组
        });
        startTime = Date.now(); // 记录开始时间
        this.startTimer(); // 启动定时器
      });
  },

  startTimer() {
    timer = setInterval(() => {
      currentQuestionTime++;
      this.setData({
        // currentTime: this.formatTime(currentQuestionTime)
        currentTime:currentQuestionTime
      });
    }, 1000);
  },


  optionChange(e) {
    let value = e.detail.value;
    this.setData({ userSelect: value });
  },

  submitAnswer() {
    let currentNum = this.data.current - 1;
    if (!this.data.userSelect) {
      wx.showToast({
        icon: 'none',
        title: '请选择答案',
      });
      return;
    }

    this.setData({
      answered: this.data.answered.map((v, index) => index === currentNum ? true : v)
    });

    let that = this;
    wx.cloud.database().collection('timu').where({
      type: "单选",
      _id: this.data.subject._id
    }).get().then(res => {
      if (res.data.length > 0) {
        let explainData = res.data[0].explain;
        let correctAnswer = res.data[0].answer;
        that.setData({
          correctAnswer,
          explain: explainData
        });
        let options = that.data.subject.options;
        for (let i = 0; i < options.length; i++) {
          if (options[i].code === that.data.userSelect) {
            options[i].color = that.data.userSelect === correctAnswer ? '#32CD32' : 'red';
          } else {
            options[i].color = 'black';
          }
        }

        that.setData({
          subject: {
            ...that.data.subject,
            options
          }
        });

        let score = calculateScore(that.data.userSelect, res.data[0].answer);
        that.setData({
          userScore: score
        });

        if (score === 1) { // 用户答对题目时，增加correctCount
          that.setData({
            correctCount: that.data.correctCount + 1
          });
        }

        let errorCount = collectCuoti(that.data.userSelect, res.data[0].answer);
        if (errorCount) {
          that.setData({
            totalError: that.data.totalError + 1
          });
          that.saveCuotiToDatabase(res.data[0], that.data.userSelect);
        }

        if (currentNum === titles.length - 1) {
          that.setData({
            totalScore: that.data.userScore,
            totalError: that.data.totalError,
            showFinishButton: true
          });
        }
      }
    });
  },

  saveCuotiToDatabase(questionData, userAnswer) {
    const openid = wx.getStorageSync('openid');
    const db = wx.cloud.database();
    const usersCollection = db.collection('users');

    // 查询用户记录
    usersCollection.where({
      openid: openid
    }).get().then(res => {
      let cuoti = res.data[0].cuoti || [];
      let existingQuestion = cuoti.find(item => item.title === questionData.title);
      if (existingQuestion) {
        // 如果存在相同标题的记录，可以选择更新或提示用户
        console.log('已存在相同标题的记录', existingQuestion);
        wx.showToast({
          title: '此题目已记录为错题',
          icon: 'none'
        });
      } else {
        // 如果不存在相同标题的记录，则插入新记录
        cuoti.push({
          questionId: questionData._id,
          title: questionData.title,
          options: this.data.subject.options,
          userAnswer: userAnswer,
          correctAnswer: questionData.answer,
          type: questionData.type,
          explain: questionData.explain,
          timestamp: new Date().toISOString() // 添加时间戳以便记录收藏时间
        });
        usersCollection.where({
          openid: openid
        }).update({
          data: {
            cuoti: db.command.set(cuoti)
          },
          success: res => {
            console.log('错题已成功保存到用户记录', res);
            wx.showToast({
              title: '错题记录成功',
              icon: 'success'
            });
          },
          fail: err => {
            console.error('保存错题失败', err);
            wx.showToast({
              title: '错题记录失败',
              icon: 'none'
            });
          }
        });
      }
    }).catch(err => {
      console.error('查询用户记录失败', err);
    });
  },

  prevQuestion() {
    let currentNum = this.data.current;
    if (currentNum > 1) {
      currentNum--;
      let subject = titles[currentNum - 1];

      this.setData({
        current: currentNum,
        subject,
        userSelect: this.data.answered[currentNum - 1] ? this.data.userSelect : '', // 如果已回答过，则保留上次的选择
        isSelect: this.data.answered[currentNum - 1],
        correctAnswer: subject.answer,
        explain: subject.explain
      });
    } else {
      wx.showToast({
        icon: 'none',
        title: '已经是第一题了',
      });
    }
  },

  nextQuestion() {
    let currentNum = this.data.current;
    if (currentNum < titles.length) {
      if (!this.data.userSelect && !this.data.answered[currentNum - 1]) {
        wx.showToast({
          icon: 'none',
          title: '请先选择答案并提交，再进入下一题',
        });
        return;
      }
      currentNum++;
      let subject = titles[currentNum - 1];
      this.setData({ current: currentNum, subject }, () => {
        // 只有当当前题已回答（answered对应位置为true）时，才去获取下一题的正确答案和解析
        if (this.data.answered[currentNum - 1]) {
          let that = this;
          wx.cloud.database().collection('timu').where({ type: "单选", _id: subject._id }).get().then(res => {
            if (res.data.length > 0) {
              let explainData = res.data[0].explain;
              let correctAnswer = res.data[0].answer;
              that.setData({ correctAnswer, explain: explainData });
            }
          });
        } else {
          // 重置correctAnswer和explain
          this.setData({ correctAnswer: '', explain: '' });
        }
        this.setData({ userSelect: '', isSelect: false });
      });
    } else {
      wx.showToast({
        icon: 'static',
        title: '已经是最后一题了',
      });
    }
  },

  goToFinishPage() {
    clearInterval(timer); // 清除定时器
    console.log('准备传递给answer-finish页面的答题总时间和答对题目数量：', currentQuestionTime, this.data.correctCount);
    wx.redirectTo({
      url: `/pages/answer-finish/answer-finish?totalTime=${currentQuestionTime}&correctCount=${this.data.correctCount}`,
    });
  },

  // 收藏题目
  collectQuestion() {
    const questionData = {
      questionId: this.data.current,
      title: this.data.subject.title,
      options: this.data.subject.options,
      userAnswer: this.data.userSelect,
      correctAnswer: this.data.subject.answer,
      type: this.data.subject.type,
      explain: this.data.subject.explain,
      timestamp: new Date().toISOString() // 添加时间戳以便记录收藏时间
    };

    // 获取openid
    const openid = wx.getStorageSync('openid');
    const db = wx.cloud.database();
    const usersCollection = db.collection('users');

    // 查询用户记录
    usersCollection.where({
      openid: openid
    }).get().then(res => {
      let save = res.data[0].save || [];
      let existingQuestion = save.find(item => item.title === questionData.title);
      if (existingQuestion) {
        // 如果存在相同标题的记录，可以选择更新或提示用户
        console.log('已存在相同标题的记录', existingQuestion);
        wx.showToast({
          title: '此题目已收藏',
          icon: 'none'
        });
      } else {
        // 如果不存在相同标题的记录，则插入新记录
        save.push(questionData);
        usersCollection.where({
          openid: openid
        }).update({
          data: {
            save: db.command.push(save)
          },
          success: res => {
            console.log('题目已成功保存到用户记录', res);
            wx.showToast({
              title: '收藏成功',
              icon: 'success'
            });
          },
          fail: err => {
            console.error('保存题目失败', err);
            wx.showToast({
              title: '收藏失败',
              icon: 'none'
            });
          }
        });
      }
    }).catch(err => {
      console.error('查询用户记录失败', err);
    });
  },
  onUnload() {
    clearInterval(timer);
  }
});